package com.seleniti.enpareja.controller.ui.view;

import org.ioc.commons.flowcontrol.actioncontroller.ActionController;
import org.ioc.commons.flowcontrol.eventbus.EventBus;
import org.ioc.commons.flowcontrol.operationmanager.OperationManager;
import org.ioc.commons.flowcontrol.taskcontroller.RepeatingTask;
import org.ioc.commons.flowcontrol.taskcontroller.TaskHandler;
import org.ioc.commons.utils.FormatterLogger;

import com.seleniti.enpareja.controller.control.factory.EnParejaAppController;
import com.seleniti.enpareja.controller.ui.base.EnParejaViewBasePresenter;
import com.seleniti.enpareja.controller.ui.main.AppShell;
import com.seleniti.enpareja.controller.ui.view.RequiredReloadView.Action;
import com.seleniti.enpareja.controller.ui.view.RequiredReloadView.Event;
import com.seleniti.enpareja.controller.ui.view.RequiredReloadView.Operation;

/**
 * Presenter for the Login view
 * 
 * @author Jesús Lunar Pérez
 * 
 */
public class RequiredReloadPresenter
		extends
		EnParejaViewBasePresenter<RequiredReloadView, RequiredReloadView.Event, RequiredReloadView.Operation, RequiredReloadView.Action>
		implements RequiredReloadView.Presenter {

	private static final FormatterLogger logger = FormatterLogger.getLogger(RequiredReloadPresenter.class);

	private AppShell shell;

	private EnParejaAppController theApp;

	private int counter;

	private TaskHandler task;

	public RequiredReloadPresenter(RequiredReloadView display, EventBus<Event> eventbus,
			OperationManager<Operation> operationManager, ActionController<Action> actionController) {
		super(display, eventbus, operationManager, actionController);
	}
	
	@Override
	public void onInitDisplay() {
		super.onInitDisplay();
		
		this.shell = clientFactory.getShell();
		this.theApp = clientFactory.getAppController().forThisObject(this);
	}

	@Override
	public void onActive() {
		super.onActive();

		this.counter = 10; /* 10 seg. */
		this.task = taskController.scheduleDelayed(1000, new RepeatingTask() {

			@Override
			public boolean run() {
				display.counter().setValue(counter--);

				if (counter == 0) {
					onReloadNow();
				}

				return (counter > 0);
			}
		});
	}

	@Override
	public void onDeactive() {
		super.onDeactive();
		if (this.task != null) {
			this.task.cancel();
			this.task = null;
		}
	}

	@Override
	public void onReloadNow() {
		if (this.task != null) {
			this.task.cancel();
			this.task = null;
		}
		theApp.reload();
	}

}
